package cn.zk.simple.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * Handler
 * 该handler处理客户端发送的信息（打印出来），并发送信息（你好服务端！）给服务端
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 通道就绪就会触发该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 给服务器发消息
        String msg = "你好服务端200！"+System.currentTimeMillis();
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg,StandardCharsets.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取服务器的消息
        ByteBuf buf = (ByteBuf) msg;
        String message = buf.toString(StandardCharsets.UTF_8);
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println("来自服务器:"+socketAddress+"发送的消息:"+message);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        // 关闭连接
        ctx.close();
    }
}
